package com.pan.listener.impl;

import com.pan.action.MyAction;
import com.pan.listener.CommonListener;
import com.pan.listener.MyListener;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class CompareAndSetSavePressedListener extends CommonListener {

    private Set<String> set = new HashSet<>();

    private AtomicInteger flag = new AtomicInteger(1);

    private void takeFlag(){
        for (;!flag.compareAndSet(1,0););
    }

    private void returnFlag(){
        for (;!flag.compareAndSet(0,1););
    }

    @Override
    public void pressed(String key) {
        takeFlag();
        set.add(key);
        super.action.hook(set);
        returnFlag();
    }

    @Override
    public void released(String key) {
        takeFlag();
        set.remove(key);
        returnFlag();
    }

}
